package com.ford.trade.controller;

import com.ford.trade.dto.QueryDTO;
import com.ford.trade.entity.*;
import com.ford.trade.processor.*;
import com.ford.trade.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.downloader.HttpClientDownloader;
import us.codecraft.webmagic.scheduler.BloomFilterDuplicateRemover;
import us.codecraft.webmagic.scheduler.QueueScheduler;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: ford
 * @date: 2022/4/25 11:33
 */
@Slf4j
@RestController
public class TradeController {

    @Resource
    private Game500Service game500Service;
    @Resource
    private PeilvService peilvService;
    @Resource
    private FenxiService fenxiService;
    @Resource
    private AoKeGameService aoKeGameService;
    @Resource
    private OddsService oddsService;
    @Resource
    private AokeFenxiService aokeFenxiService;
    @Resource
    private Odds3Service odds3Service;


    @RequestMapping("/index")
    public String index(ModelMap map) {
        map.addAttribute("newWorld", "WELCOME TO NEW WORLD!!!");
        return "index";
    }

    @RequestMapping("/picture")
    public void picture(@RequestBody QueryDTO queryDTO) {
        PictureProcessor pictureProcessor = new PictureProcessor();
        List<String> urls = new ArrayList<>();
//                {
//                "https://wallhaven.cc/user/Calm/favorites/623697?purity=110&page=20",
//        };
        for (int i = 1; i < 2; i++) {
            urls.add("https://wallhaven.cc/user/Calm/favorites/623697?purity=110&page="+i);
        }
//        System.setProperty("https.protocols", "TLSv1.2");
        String[] a = new String[urls.size()];
        String[] strings = urls.toArray(a);
        for (int i = 0; i < strings.length; i++) {
            Spider.create(pictureProcessor)
                    .addUrl(strings[i])
                    .setDownloader(new HttpClientDownloader())
                    .setDownloader(new com.ford.trade.HttpClientDownloader())
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100)))
                    .thread(30)
                    .run();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    @PostMapping("getBisai")
    public void getBisai(@RequestBody QueryDTO queryDTO) {
        if ("500".equals(queryDTO.getUrlType())) {
            TeamProcessor teamProcessor = new TeamProcessor();
            teamProcessor.setGameService(game500Service);
            teamProcessor.setDate(queryDTO.getDate());
            teamProcessor.setUrl(queryDTO.getUrl());
            teamProcessor.setGetResult(queryDTO.getGetResult());
            Spider.create(teamProcessor)
                    .addUrl(queryDTO.getUrl())
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100)))
                    .thread(10)
                    .run();
        } else {
            AoKeTeamProcessor teamProcessor = new AoKeTeamProcessor();
            teamProcessor.setGameService(aoKeGameService);
            teamProcessor.setWeek(queryDTO.getDate());
            teamProcessor.setUrl(queryDTO.getUrl());
            teamProcessor.setGetResult(queryDTO.getGetResult());
            Spider.create(teamProcessor)
                    .addUrl(queryDTO.getUrl())
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100)))
                    .thread(10)
                    .run();
        }
    }

    @PostMapping("getPeilv")
    public void getPeilv(@RequestBody QueryDTO queryDTO) throws ParseException {
        List<Game> allByDateAfter = game500Service.findAllByDateBetten(queryDTO.getDate());
        if (CollectionUtils.isEmpty(allByDateAfter)) {
            return;
        }
        List<String> urls = new ArrayList<>();
        for (Game game : allByDateAfter) {
            for (int i = 1; i < 5; i++) {
                urls.add("https://odds.500.com/fenxi/ouzhi-" + game.getIndexId() + ".shtml" + "?ctype=" + i);
            }
        }
        for (Game game : allByDateAfter) {
            urls.add("https://odds.500.com/fenxi/ouzhi-" + game.getIndexId() + ".shtml" + "?order=0");

        }
        String[] objects = new String[allByDateAfter.size()];
        String[] array = urls.toArray(objects);
        PeilvProcessor peilvProcessor = new PeilvProcessor();
        peilvProcessor.setCookie(queryDTO.getCookie());
        peilvProcessor.setPeilvService(peilvService);
        peilvProcessor.setDate(queryDTO.getDate());
        Spider.create(peilvProcessor)
                .addUrl(array)
                .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100)))
                .thread(32)
                .run();
    }

    @PostMapping("getOdds")
    public String getOdds(@RequestBody QueryDTO queryDTO) throws IOException, ParseException {
        List<AoKeGame> allByDateAfter = aoKeGameService.findAllByDateBetten(queryDTO.getDate());
        if (CollectionUtils.isEmpty(allByDateAfter)) {
            return "未查询到比赛";
        }
        List<String> urls = new ArrayList<>();
//        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/" + queryDTO.getUrl());

        //https://www.okooo.com/soccer/match/1166629/odds/ajax/?page=0&trnum=5&companytype=BaijiaBooks&type=1
//        for (AoKeGame aoKeGame : allByDateAfter) {
        //百家欧赔
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/");
        //无交易所
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=90&companytype=ExceptExchangeMakerID&type=1");
        //交易所
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=30&companytype=ExchangeBooks&type=1");
        //权威博彩公司
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=8&companytype=AuthoriteBooks&type=1");
        //bigCompany
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=28&companytype=BigBooks&type=1");
        //小公司
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=5&companytype=SmallBooks&type=1");
        //赛事专用公司
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=3&companytype=LeagueBooks&type=1");
        //我的自选公司1
//            urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=5&companytype=MyOddsBooks1&type=1");
        //我的自选公司2
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(queryDTO.getIndexId()).getIndexId() + "/odds/ajax/?page=0&trnum=5&companytype=MyOddsBooks2&type=1");
//
//        }

        String[] objects = new String[allByDateAfter.size()];
        String[] array = urls.toArray(objects);
        AoKeOddsProcessor aoKeOddsProcessor = new AoKeOddsProcessor();
        aoKeOddsProcessor.setCookie(queryDTO.getCookie());
        aoKeOddsProcessor.setOddsService(oddsService);
        aoKeOddsProcessor.setDate(queryDTO.getDate());
//        String ips = CoreHttpUtils.get("http://www.padaili.com/proxyapi?api=idGh1DCozWbcnVuGxqJzYaz5Cpa8KjTl&num=100&type=3&order=jiance");
//        String[] split = ips.split("<br/>");
////        Random random = new Random();
////        String ip = split[random.nextInt(split.length)];
////        Proxy proxy = new Proxy(queryDTO.getIp().split(":")[0], Integer.valueOf(queryDTO.getIp().split(":")[1]));
//
//        //创建下载器
        HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
//        List<Proxy> proxies = new ArrayList<>();
//        for (String ip : split) {
//            proxies.add(new Proxy(queryDTO.getIp().split(":")[0], Integer.valueOf(queryDTO.getIp().split(":")[1])));
////            proxies.add(new Proxy(ip.split(":")[0], Integer.valueOf(ip.split(":")[1])));
//        }
//        Proxy[] proxies1 = new Proxy[split.length];
//        Proxy[] proxies2 = proxies.toArray(proxies1);
//        //设置代理服务器
//        httpClientDownloader.setProxyProvider(SimpleProxyProvider.from(proxies2));
////        Html download = httpClientDownloader.download("https://www.okooo.com/");
        Request request = new Request();
////        urls.add("https://www.okooo.com/soccer/match/" + aoKeGame.getIndexId() + "/odds/ajax/?page=0&trnum=3&companytype=LeagueBooks&type=1");
//
//        request.setUrl("https://www.okooo.com/soccer/match/" + allByDateAfter.get(0).getIndexId() + "/odds/ajax/?page=0&trnum=3&companytype=LeagueBooks&type=1");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", 0);
        params.put("trnum", 60);
        params.put("companytype", "AuthoriteBooks");
        params.put("type", 1);
        request.setExtras(params);
        for (int i = 0; i < 8; i++) {
            request.setUrl(urls.get(i));
            Spider.create(aoKeOddsProcessor)
                    .addRequest(request)
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100)))
                    .thread(1)
                    .run();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "比赛总数:" + allByDateAfter.size() + "\n当前比赛：" + allByDateAfter.get(queryDTO.getIndexId()).toString();
    }

    @PostMapping("getOdds2")
    public String getOdds2(@RequestBody QueryDTO queryDTO) throws IOException, ParseException {
        List<AoKeGame> allByDateAfter = aoKeGameService.findAllByDateBetten(queryDTO.getDate());
        log.info("比赛总数：" + allByDateAfter.size());
        if (CollectionUtils.isEmpty(allByDateAfter)) {
            return "未查询到比赛";
        }
        List<String> urls = new ArrayList<>();
        for (AoKeGame aoKeGame : allByDateAfter) {
            //我的自选公司2
            urls.add("https://www.okooo.com/soccer/match/" + aoKeGame.getIndexId() + "/odds/ajax/?page=0&trnum=5&companytype=MyOddsBooks&type=1");
        }

        String[] objects = new String[allByDateAfter.size()];
        String[] array = urls.toArray(objects);
        AoKeOddsProcessor aoKeOddsProcessor = new AoKeOddsProcessor();
        aoKeOddsProcessor.setCookie(queryDTO.getCookie());
        aoKeOddsProcessor.setOddsService(oddsService);
        aoKeOddsProcessor.setDate(queryDTO.getDate());

        Request request = new Request();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", 0);
        params.put("trnum", 30);
        params.put("companytype", "MyOddsBooks");
        params.put("type", 1);
        request.setExtras(params);
        for (String url : urls) {
            request.setUrl(url);
            Spider.create(aoKeOddsProcessor)
                    .addRequest(request)
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100)))
                    .thread(1)
                    .run();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "比赛总数:" + allByDateAfter.size() + "\n当前比赛：" + allByDateAfter.get(queryDTO.getIndexId()).toString();
    }


    /**
     * 老张预测算法
     *
     * @param fenxi
     */
    private void predictChoose(Fenxi fenxi) {
        //初始赔率看法
        String doubleChoose = fenxi.getPeilv();
        //让球
        Integer rangQiu = fenxi.getRangQiu();
        //凯利值看法
        List<Integer> kelly = new ArrayList<>();
        //凯里差值
        List<Integer> kellyChaZhi = new ArrayList<>();


    }

    void setType(String type, Fenxi fenxi, String value, Integer chazhi) {
        //全部公司
        //
        //交易所
        //非交易所
        //威立I
        //威立BI
        //交易所
        //竞彩6
        if ("全部公司".equals(type)) {
            fenxi.setAllCompany(value);
            fenxi.setChaZhiAll(chazhi);
        } else if ("主流".equals(type)) {
            fenxi.setZhuliu(value);
            fenxi.setChaZhiZhuliu(chazhi);
        } else if ("交易所".equals(type)) {
            fenxi.setJiaoYiSuo(value);
            fenxi.setChaZhiJiaoYiSuo(chazhi);
        } else if ("非交易所".equals(type)) {
            fenxi.setUnJiaoYiSuo(value);
            fenxi.setChaZhiUnJiaoYiSuo(chazhi);
        } else if ("威立I".equals(type)) {
            fenxi.setWlw(value);
            fenxi.setChaZhiWlw(chazhi);
        } else if ("威立BI".equals(type)) {
            fenxi.setChaZhiWlwb(chazhi);
            fenxi.setWlwb(value);
        } else if ("威立澳BI".equals(type)) {
            fenxi.setChaZhiWlwba(chazhi);
            fenxi.setWlwba(value);
        } else if ("竞彩6".equals(type)) {
            fenxi.setWlwbaj(value);
            fenxi.setChaZhiWlwbaj(chazhi);
        }
    }



    @PostMapping("getOdds3")
    public String getOdds3(@RequestBody QueryDTO queryDTO) throws IOException, ParseException {
        List<AoKeGame> allByDateAfter = aoKeGameService.findAllByDateBetten(queryDTO.getDate());
        if (CollectionUtils.isEmpty(allByDateAfter)) {
            return "未查询到比赛";
        }
        List<String> urls = new ArrayList<>();
        List<AoKeGame> collect = allByDateAfter.stream().limit(10).collect(Collectors.toList());
        for (AoKeGame aoKeGame : collect) {
            urls.add("https://www.okooo.com/soccer/match/" + aoKeGame.getIndexId() + "/odds/ajax/?page=0&trnum=0&companytype=MyOddsBooks2&type=1");
        }
        urls.add("https://www.okooo.com/soccer/match/" + allByDateAfter.get(0).getIndexId() + "/odds/ajax/?page=0&trnum=0&companytype=MyOddsBooks2&type=1");
        //百家欧赔
        AoKeOdds3Processor aoKeOddsProcessor = new AoKeOdds3Processor();
//        aoKeOddsProcessor.setCookie(queryDTO.getCookie());
        aoKeOddsProcessor.setOddsService(odds3Service);
        aoKeOddsProcessor.setDate(queryDTO.getDate());
//        //创建下载器
//        Request request = new Request();
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("page", 0);
//        params.put("trnum", 60);
//        params.put("companytype", "BaijiaBooks");
//        params.put("type", 1);
//        request.setExtras(params);
        for (int i = 0; i < urls.size(); i++) {
//            request.setUrl(urls.get(i));
            Spider.create(aoKeOddsProcessor)
                    .addUrl(urls.get(i))
//                    .setDownloader(new HttpClientDownloader())
//                    .addRequest(request)
                    .setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(1)))
                    .thread(1)
                    .run();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "比赛总数:" + allByDateAfter.size();
    }

}
